package com.shuma.utils.redis;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }
    public <T> T get(String key,Class<T> type) {
        return JSONUtil.toBean(stringRedisTemplate.opsForValue().get(key), type);
    }

    // 逻辑过期
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    // 缓存穿透
    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit){
        //获取缓存数据
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        //命中缓存
        //命中的是否是空值
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null){
            return null;
        }

        //未命中缓存
        R r = dbFallback.apply(id);
        if (r == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"", time,unit);

            return r;
        }

        //将数据库获取的数据放入缓存
        this.set(key,r,time,unit);

        return r;
    }
    // 逻辑过期
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 逻辑过期
    public <R,ID> R queryWithLogicExpire(
            String keyPrefix, ID id,String lock, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit
    ){
        //1.获取缓存数据
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        //2.命中缓存
        //命中的是否是空值
        if (StrUtil.isBlank(json)) {
            //3.不存在 不为热点数据 直接返回
            return null;
        }

        //4.命中 先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //5.判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //5.1.未过期 直接返回店铺数据
            return r;
        }
        //5.2.已过期 需要缓存重建
        //6.缓存重建
        //6.1获取互斥锁
        String lockKey = lock + id;
        boolean isLock = tryLock(lockKey);
        //6.2判断锁是否获取成功
        if (isLock){
            //6.3成功 开启独立线程执行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    saveR2Redis(key,id,LocalDateTime.now().plusSeconds(unit.toSeconds(time)),r);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }

        //6.4返回过期商铺信息
        return r;
    }


    public<R,ID> void saveR2Redis(String key,ID id, LocalDateTime localDateTime, R r){
        //1.查询数据
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(r);
        redisData.setExpireTime(localDateTime);
        //3.写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    //获取互斥锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放互斥锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

}
